import axios from 'axios'
import router from '@/router/index'
import Element from "element-ui"
import $message from '@/utils/message'
const request = axios.create({
  baseURL: 'http://k5a22t.natappfree.cc/api',
  timeout: 30000,
  headers: {
    'Content-Type': "application/json"
  }
});

request.interceptors.request.use(config => {
  config.headers['Authorization'] = localStorage.getItem("token")
  return config
}, error => {
  return Promise.reject(error);
})

// 添加响应拦截器
request.interceptors.response.use(
  response => {
    const headers = response.headers
    if (headers['content-type'] === 'application/octet-stream;charset=UTF-8') {
      return response.data
    }

    let res = response.data
    if (res.code === 200) {
      return response
    } else {
      Element.Message.error(!res.msg ? '系统异常' : res.msg)
      if (res.msg === "请先登陆！") {
        router.push("/login")
      }
      return Promise.reject(response.data.msg)
    }
  },
  error => {
    console.log(error)
    if (error.response.data) {
      error.massage = error.response.data.msg
    }
    if (error.response.status === 403) {
      router.push("/login")
    }
    Element.Message.error(error.massage, {
      duration: 3000
    })
    return Promise.reject(error)
  }
)

export default request
